package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1. 判断传入参数中账号密码是否为空
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "账号或密码不能为空");
        }
        //根据传入用户名查询用户信息
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码错误");
        }
        //判断用户状态  9为正常用户
        if (AdminConstants.PASS_AUTH != wmUser.getStatus().intValue()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //2. 检查密码是否正确
        String password = wmUser.getPassword();//密码
        String salt = wmUser.getSalt();//盐
        String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());

        if (!password.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //3. 修改最近登录时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);

        //4. 颁发token
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",wmUserVO);

        return ResponseResult.okResult(map);
    }
}
